package com.woniu.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Snowflake;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniu.commons.exception.YogaException;
import com.woniu.commons.model.Result;
import com.woniu.util.FileUtil;
import com.woniu.commons.util.JwtUtil;
import com.woniu.util.OSSUtil;
import com.woniu.commons.util.RedisUtil;
import com.woniu.model.dto.YGoodsDto;
import com.woniu.model.form.*;
import com.woniu.model.model.YGoods;
import com.woniu.model.param.*;
import com.woniu.service.YGoodsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.UUID;

import static jdk.nashorn.internal.runtime.regexp.joni.Config.log;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 吴彦祖
 * @since 2024年05月23日
 */
@RestController
@RequestMapping("/yGoods")
@Api(tags = "商城商品的接口")
public class YGoodsController {

    @Resource
    private YGoodsService goodsService;
    @Resource
    private RedisUtil redisUtil;


    /**
     * 修改购物车里面商品的数量
     * @param form goodsId;商品id
     *             userId;用户id
     *             number;修改的数量
     * @param token
     * @return
     * @throws YogaException
     */
    @PostMapping("/changShoppingCarNumber")
    @ApiOperation(value = "修改购物车里面商品的数量")
    public Result changShoppingCarNumber(@RequestBody ChangShoppingCarNumberForm form, @RequestHeader String token) throws YogaException {
        String refreshToken = redisUtil.get(token);
        int accountId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("id").toString());
        ChangShoppingCarNumberParam param = BeanUtil.toBean(form, ChangShoppingCarNumberParam.class);
        param.setUserId(accountId);
        goodsService.changShoppingCarNumber(param);

        return Result.newInstance(null).setMsg("修改成功").setCode(200);
    }


    /**
     * 删除我的购物车里面的商品
     * @param GoodSId：商品id
     * @param number：数量
     * @param token：用户id
     * @return
     * @throws YogaException
     */
    @GetMapping("/delShoppingCar")
    @ApiOperation(value = "删除我的购物车里面的商品")
    public Result delShoppingCar(@RequestParam("GoodSId") Integer GoodSId, @RequestParam("number") Integer number, @RequestHeader String token) throws YogaException {

        String refreshToken = redisUtil.get(token);
        int accountId = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("userId").toString());
        AddShoppingCarParam param = new AddShoppingCarParam();
        param.setUserId(accountId);
        param.setNumber(number);
        param.setGoodSId(GoodSId);

        goodsService.delShoppingCar(param);
        return Result.newInstance(null).setMsg("删除购物车成功").setCode(200);
    }


    /**
     * 添加商品到我的购物车
     * @param GoodSId：商品id
     * @param number：数量
     * @param token：用户id
     * @return
     * @throws YogaException
     */
    @GetMapping("/addShoppingCar")
    @ApiOperation(value = "添加商品到我的购物车")
    public Result addShoppingCar(@RequestParam("GoodSId") Integer GoodSId, @RequestParam("number") Integer number, @RequestHeader String token) throws YogaException {

        String refreshToken = redisUtil.get(token);
        Integer Id = Integer.parseInt(JwtUtil.parseToken(refreshToken).get("userId").toString());

        AddShoppingCarParam param = new AddShoppingCarParam();
        param.setNumber(number);
        param.setGoodSId(GoodSId);
        param.setUserId(Id);
        goodsService.addShoppingCar(param);

        return Result.newInstance(null).setMsg("添加购物车成功").setCode(200);
    }


    /**
     * 新增商品
     *
     * @param form form:goodsName;商品名
     *             goodsPrice;商品价格
     *             goodsNum;商品数量
     * @return
     * @throws Exception
     */
    @PostMapping("insert")
    @ApiOperation(value = "新增商品的接口")
    public Result bookInfoAdd(@RequestBody GoodsInsertForm form) throws Exception {

        goodsService.InsertBookInfo(BeanUtil.toBean(form, GoodsInsertParam.class));

        return Result.newInstance(null).setMsg("新增成功").setCode(200);
    }

    /**
     * 下架商品
     *
     * @param goodsId：商品id
     * @return
     * @throws YogaException
     */
    @GetMapping("/disable")
    @ApiOperation(value = "下架商品")
    public Result disable( Integer goodsId) throws YogaException {
        goodsService.disable(goodsId);
        return Result.newInstance(null).setCode(200).setMsg("下架成功");
    }

    /**
     * 上架商品
     *
     * @param goodsId：商品id
     * @return
     * @throws YogaException
     */
    @GetMapping("/enable")
    @ApiOperation(value = "上架商品")
    public Result enable(Integer goodsId) throws YogaException {
        goodsService.enable(goodsId);
        return Result.newInstance(null).setCode(200).setMsg("启用成功");
    }

    /**
     * 修改商品图片
     *
     * @param form
     * @return
     * @throws Exception
     */
    @PostMapping("updateImage")
    @ApiOperation(value = "修改商品图片接口")
    public Result GoodsUpdataImage(GoodsUpdataImageForm form) throws Exception {

        // @RequestBody不能加，因为本次请求是传了文件的，不加该注解;文件只能用表单参数
        if (!FileUtil.isImageFile(form.getImage().getInputStream())) {
            throw new Exception("文件类型有误，请检查");
        }

        String oldname = form.getImage().getOriginalFilename();
        //获取上传文件的原始文件名。

        String substring = oldname.substring(oldname.lastIndexOf("."));
        //获取上传文件的后缀名。

        String filename = new Snowflake(1, 1).nextIdStr();
        //生成一个雪花作为文件名

        String filePath = OSSUtil.uploadFile(form.getImage().getInputStream(), filename + substring, "hugedehome");
        //调用 OSSUtil 工具类的 uploadFile() 方法，将上传的文件保存到阿里云 OSS 存储中。该方法接受文件的输入流、文件名和存储桶名称作为参数，并返回上传文件的路径。

        System.out.println(filePath+"上传到oss的名字");

        GoodsUpdataImageParam param = BeanUtil.toBean(form, GoodsUpdataImageParam.class);

        param.setGoodsImage(filePath);
        //传文件的路径设置到 BookInsertParam 对象中，作为图书的封面图片路径。

        System.out.println(filePath+"存到数据库的名字");

        goodsService.updateimage(param);

        return Result.newInstance(null).setMsg("修改成功").setCode(200);
    }





    /**
     * 传一个对象，根据id去修改里面的信息
     * 在商城订单里面用了，用于去修改商品的冻结量和数量
     *
     * @param ygoods 商品对象
     * @return
     * @throws YogaException
     */
    @PostMapping("/updateByIdGoods")
    @ApiOperation(value = "传一个对象，根据id去修改里面的信息")
    public Result updateByIdGoods(@RequestBody YGoods ygoods) throws YogaException {
        goodsService.updateByIdGoods(ygoods);
        return Result.newInstance(null).setMsg("修改成功").setCode(200);
    }


    /**
     * 修改商品信息
     *
     * @param form //商品id goodsId;
     *             //商品名 goodsName;
     *             //商品价格 goodsPrice;
     *             //商品数量 goodsNum;
     * @return
     * @throws YogaException
     */
    @PostMapping("/updateGoodsMessage")
    @ApiOperation(value = "修改商品信息接口")
    public Result updateGoodsMessage(GoodsUpdataMessageForm form) throws YogaException {
        goodsService.updateGoodsMessage(BeanUtil.toBean(form, GoodsUpdataMessageParam.class));
        return Result.newInstance(null).setMsg("修改成功").setCode(200);
    }

    /**
     * 分页查询
     *
     * @param form pageNum;pageSize;
     * @return
     * @throws YogaException
     */
    @GetMapping("/loadPageGoods")
    @ApiOperation(value = "分页查询商品接口")
    public Result loadPageGoods( PageForm form) throws YogaException {
        Page<YGoods> page = goodsService.loadPageGoods(BeanUtil.toBean(form, PageParam.class));
        return Result.newInstance(Page.class).setMsg("查询成功").setCode(200).setData(page);
    }

    /**
     * 通过多个商品ID查询商品集合回去
     *
     * @param id 多个商品id
     * @return
     * @throws YogaException
     */
    @PostMapping("/listById")
    @ApiOperation(value = "通过多个商品ID查询商品集合回去")
    public Result<List<YGoodsDto>> listById(@RequestBody Set<Integer> id) throws YogaException {
        List<YGoods> yGoods = goodsService.listByIds(id);
        if (yGoods == null) {
            return Result.newListInstance(YGoodsDto.class).setData(BeanUtil.copyToList(yGoods, YGoodsDto.class)).setCode(500);
        }
        return Result.newListInstance(YGoodsDto.class).setData(BeanUtil.copyToList(yGoods, YGoodsDto.class));
    }

    /**
     * 通过一个商品ID查询一个商品回去
     *
     * @param id ：商品id
     * @return 一个商品
     */
    @GetMapping("/byId/{id}")
    @ApiOperation(value = "通过一个商品ID查询一个商品回去")
    public Result<YGoodsDto> byId(@PathVariable("id") Integer id) {
        YGoods yGoods = goodsService.getById(id);
        return Result.newInstance(YGoodsDto.class).setData(BeanUtil.toBean(yGoods, YGoodsDto.class));
    }





}

